package com.zsy.controller;
import com.zsy.pojo.Employee;
import com.zsy.pojo.Page;
import com.zsy.pojo.R;
import com.zsy.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        R<Employee> result = employeeService.login(employee);

        if(result.getCode()==1){
            //取出Employee中的id并存入回话域
            session.setAttribute("result",result.getData().getId());
        }
        return result;
    }


    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        //销毁回话域
        session.invalidate();
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpSession session){
        //获取创建此员工账号的id
        long empid = (long) session.getAttribute("result");
        //填补创建者和修改者
        employee.setCreateUser(empid);
        employee.setUpdateUser(empid);
        //调用Sevice层保存数据，在Service设置创建时间和修改时间，以及状态，和密码
        employeeService.save(employee);

        return R.success("保存成功");
    }

    @GetMapping("/page")
    public R<Page<Employee>> page(Integer page,Integer pageSize,String name){

        Page<Employee> byPage = employeeService.findByPage(page, pageSize, name);


        return R.success(byPage);
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        long result = (long) session.getAttribute("result");
        employee.setUpdateUser(result);

        employeeService.update(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        Employee byId = employeeService.findById(id);

        return R.success(byId);
    }
}
